import React from 'react';
import { Icon, Modal } from 'antd-mobile';
import style from './HomeModal.less';
import { connect } from 'dva';
import moment from "moment/moment";
import classnames from 'classnames';

class HomeModal extends React.Component {

  state = {
    modal: false,
    modalType: 1,
    doubleAuthority: false,  // 是否同时具有店长、导购权限

    headerHeight: '2.1em',
  };


  componentWillMount() {
    const { roles, phone, salemanId } = this.props.auth.currentUser;
    const data = localStorage.getItem('modalData');
    const currentData = `${moment().format('MM-DD')}/${phone}`;
    if (data !== currentData) {
      
      if (roles.indexOf('salesman') === -1) {
        this.init(2);
      } else {
        this.init(1);
      }
      if (roles.indexOf('manager') !== -1 && salemanId) {
        this.setState({
          doubleAuthority: true,
        });
      }
    }
  }

  init(num) {
    const startDate = moment().startOf('month').format('YYYY-MM-DD');
    const endDate = moment().add(1, 'months').startOf('month').format('YYYY-MM-DD');
    if (num === 1) {
      const { salemanId } = this.props.auth.currentUser;
      this.props.dispatch({ type: 'stat/fetchStatMyAchv', payload: { startDate, endDate, salemanId } });
      this.props.dispatch({ type: 'stat/fetchSalesmanVisitStat', payload: { startDate, endDate } });
    } else if (num === 2) {
      this.props.dispatch({ type: 'stat/fetchStatMyAchv', payload: { startDate, endDate } });
      this.props.dispatch({
        type: 'stat/fetchStatTasks',
        payload: { startDate, endDate },
      });
    }
    this.setState({
      modal: true,
      modalType: num,
    }, () => {
      if (num === 1) {
        this.setState({ headerHeight: document.querySelector('.am-modal').offsetHeight * 0.06 + 'px' });
      } else {
        this.setState({ headerHeight: document.querySelector('.am-modal').offsetHeight * 0.05 + 'px' });
      }
    });
  }

  onClose = () => {
    const { roles, phone, salemanId } = this.props.auth.currentUser;
    const currentData = `${moment().format('MM-DD')}/${phone}`;
    localStorage.setItem('modalData', currentData);

    this.setState({
      modal: false,
    });
  }

  yesterdayDate = () => {
    const { statMyAchv } = this.props.stat;
    let data = 0;
    if (statMyAchv) {
      const str = moment().subtract(1, 'days').format('MM-DD');

      for (const item of statMyAchv.data) {
        if (item._id === str) {
          data = item.total_money;
        }
      }
    }
    return data.toFixed(2);
  }

  randomStr = () => {
    const arr = [
      "每一个客户都是机会，向着梦想出发吧！",
      "越努力越幸运，不要错过每一个机会哦~",
      "成功没有捷径，唯有不断的坚持~",
      "努力的人业绩都不会太差，今天比昨天更强大",
    ];
    return arr[Math.floor(Date.now() / 1000 / 60 / 60 / 24) % arr.length];
  }

  clickHeader = (type) => {
    const { modalType } = this.state;
    if (type !== modalType) {
      this.init(type);
    }
  }

  render() {
    const saleManName = this.props.auth.currentUser.saleManName || '';
    const { statMyAchv } = this.props.stat;
    const { modalType, doubleAuthority, headerHeight } = this.state;
    const { count = 0, realCount = 0, successCount = 0, completePercentage = 0, successPercentage = 0, successTotalMoney = 0 } = modalType === 1 ? this.props.stat.salesmanVisitStat : this.props.stat.statTasks;
    const { total = 0 } = this.props.task;
    return (
      <Modal
        className={classnames({
          [style.modalTask]: true,
          [style.modalType1]: modalType === 1 && !doubleAuthority,
          [style.modalType2]: modalType === 2 && !doubleAuthority,
          [style.modalType3]: modalType === 1 && doubleAuthority,
          [style.modalType4]: modalType === 2 && doubleAuthority,
        })}
        transparent
        maskClosable={false}
        visible={this.state.modal}
        platform="ios"
        footer={[{ text: <Icon type="cross-circle" size="lg" className={style.icon} onClick={this.onClose} /> }]}
      >
        {
          doubleAuthority &&
          <div className={style.header}>
            <span
              onClick={this.clickHeader.bind(this, 2)} style={{ height: headerHeight, lineHeight: headerHeight }}
              className={classnames({
                [style.selection]: true,
                [style.active]: modalType === 2,
              })}
            />
            <span
              onClick={this.clickHeader.bind(this, 1)} style={{ height: headerHeight, lineHeight: headerHeight }}
              className={classnames({
                [style.selection]: true,
                [style.active]: modalType === 1,
              })}
            />
          </div>
        }
        <div className={style.selection1}>
          <div className={style.name}>Hi，{saleManName}</div>
          <div className={style.tip1}>
            {modalType === 1 ? '以下是您的业绩情况，加油哦！' : '以下是您门店的业绩情况'}
          </div>
          <div className={style.sale}>昨日销售(元)
            <span className={style.data}>{this.yesterdayDate()}</span>
          </div>
          <div className={style.sale}>本月销售(万元)
            <span className={style.data}>{(statMyAchv ? statMyAchv.total_money : 0).toFixed(2)}</span>
          </div>
        </div>

        <div
          className={classnames({
            [style.center]: true,
            [style.center1]: modalType === 1,
            [style.center2]: modalType === 2,
          })}
        >
          <div className={style.selection2}>
            <div>本月成功转化金额(元)</div>
            <div className={style.data}>{Number(successTotalMoney).toFixed(2)}</div>
            <div className={style.data2}>本月成功转化{successCount}人</div>
          </div>

          <div className={style.selection3}>
            <div className={style.flex1}>
              <img src={require('../../assets/modal1.png')} alt="" />
              <div className={style.flex2}>
                <div className={style.ellipsis}>本月回访完成率</div>
                <div className={style.data}>{completePercentage.toFixed(2)}%</div>
              </div>
            </div>
            <div className={style.flex1}>
              <img src={require('../../assets/modal2.png')} alt="" />
              <div className={style.flex2}>
                <div className={style.ellipsis}>本月回访转化率</div>
                <div className={style.data}>{successPercentage.toFixed(2)}%</div>
              </div>
            </div>
          </div>

          <div className={style.selection4}>
            <div className={style.tip1}>您{modalType === 1 ? '' : '门店'}今天还有<span
              className={style.data}
            >{modalType === 2 ? total : total}</span>个待跟进客户
            </div>
            <div className={style.tip2}>{this.randomStr()}</div>
          </div>
        </div>
      </Modal>
    );
  }
}

export default connect(({ auth, stat, task }) => ({ auth, stat, task }))(HomeModal);
